package org.sky.security.support;
import java.util.*;

import org.sky.sys.entity.SysRole;
import org.sky.sys.entity.SysUser;
import org.sky.sys.service.SysRoleService;
import org.sky.sys.util.BspUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author weifx
 * @Title: SecurityUser
 * @ProjectName springboot-platform
 * @Description: TODO{SpringSecurity安全框架用户}
 * @date 2019/2/28 16:14
 * @Version 1.0
 */
public class SecurityUser extends SysUser implements UserDetails {
    private static final long serialVersionUID = 1L;
    /**
     * 登录Ip
     */
    private String LoginIp;
    /**
     * 登录日期
     */
    private Date loginDate;

    public SecurityUser(SysUser user) {
        if(user != null){
            this.setId(user.getId());
            this.setCode(user.getCode());
            this.setName(user.getName());
            this.setEmail(user.getEmail());
            this.setPassword(user.getPassword());
        }
    }
    /*
     * 组装用户角色信息
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        String userCode = this.getCode();
        SysRoleService sysRoleService = BspUtils.getBean(SysRoleService.class);
        List<SysRole> userRoles = sysRoleService.selectSysRoleByUserCode(userCode);
        if(userRoles != null){
            for (SysRole role : userRoles) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getCode());
                authorities.add(authority);
            }
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return super.getPassword();
    }

    @Override
    public String getUsername() {
        return super.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public String getLoginIp() {
        return LoginIp;
    }

    public void setLoginIp(String loginIp) {
        LoginIp = loginIp;
    }

    public Date getLoginDate() {
        return loginDate;
    }

    public void setLoginDate(Date loginDate) {
        this.loginDate = loginDate;
    }

    public boolean equals(Object rhs) {
        return rhs instanceof SecurityUser ? this.getCode().equals(((SecurityUser)rhs).getCode()) : false;
    }

    public int hashCode() {
        return this.getCode().hashCode();
    }
}